<template>
  <div class="mainStyle">
    <div class="role-choose contentRight">
      <role-manage :role="currentUser" v-if="currentUser"></role-manage>
      <div v-if="role === '普通用户'" class="basics-item">
        <img src="../../assets/image/user.png" class="role-item" alt="" />
        <p>ID:{{ $store.state.user.id }}</p>
        <p>姓名：{{ $store.state.user.username }}</p>
        <p>
          角色：<el-tag>
            {{ $store.state.user.groups[0] ? $store.state.user.groups[0].name : '游客' }}</el-tag
          >
        </p>
        <el-button size="small" @click="logout">切换账号</el-button>
        <el-button size="small" @click="handleClickReset($store.state.user.username)"
          >修改密码</el-button
        >
        <el-button size="small" @click="logout">用户登出</el-button>
        <log></log>
      </div>
      <div v-if="role === '游客'" class="basics-item">
        <img src="../../assets/image/user.png" class="role-item" alt="" />
        <p>ID:{{ $store.state.user.id }}</p>
        <p>姓名：{{ $store.state.user.username }}</p>
        <p>
          角色：<el-tag>
            {{ $store.state.user.groups[0] ? $store.state.user.groups[0].name : '游客' }}</el-tag
          >
        </p>
        <el-button size="small" @click="logout">切换账号</el-button>
      </div>
      <div v-if="role === '超级管理员' || role === '管理员'">
        <div class="root-item">
          <div class="role-container">
            <img src="../../assets/image/user.png" class="role-item" alt="" />
          </div>
          <div class="role-container">
            <p>ID:{{ $store.state.user.id }}</p>
            <p>姓名：{{ $store.state.user.username }}</p>
            <p>
              角色：<el-tag>
                {{
                  $store.state.user.groups[0] ? $store.state.user.groups[0].name : '游客'
                }}</el-tag
              >
            </p>
          </div>
          <div class="btn-line">
            <el-button size="small" @click="logout">用户登出</el-button>
            <el-button size="small" @click="handleClickReset($store.state.user.username)"
              >修改密码</el-button
            >
          </div>
          <el-button size="small" class="float-btn" type="primary" @click="showAddUser = true"
            >添加成员</el-button
          >
          <el-table size="small" :data="tableData" border style="width: 100%">
            <el-table-column prop="id" label="ID"></el-table-column>
            <el-table-column prop="username" label="用户名"></el-table-column>
            <el-table-column prop="last_login" label="上次登录"></el-table-column>

            <el-table-column prop="role" label="角色">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.groups"
                  placeholder="角色"
                  :disabled="$store.state.user.groups[0].name === '管理员'"
                  size="small"
                  @change="handleChangeGroup(scope.row.username, scope.row.groups)"
                >
                  <el-option
                    :label="item.name"
                    :value="item.name"
                    v-for="item in groupList"
                    :key="item.id"
                  />
                </el-select>
              </template>
            </el-table-column>

            <el-table-column prop="role" label="操作">
              <template slot-scope="scope">
                <el-button
                  size="small"
                  :disabled="
                    role === '管理员' &&
                    (scope.row.groups === '超级管理员' || scope.row.groups === '管理员')
                  "
                  type="danger"
                  @click="dellteUser(scope.row.username)"
                  >删除</el-button
                >
                <el-button
                  size="small"
                  v-if="role === '超级管理员'"
                  @click="handleClickReset(scope.row.username)"
                  >修改密码</el-button
                >
                <el-button
                  size="small"
                  v-if="role === '超级管理员' || role === '管理员'"
                  :disabled="scope.row.groups === '超级管理员'"
                  @click="editUserFile(scope.row)"
                  >编辑文件权限</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-dialog
          top="10px"
          width="1000px"
          title="创建用户"
          :visible.sync="showAddUser"
          :close-on-click-modal="false"
          :modal-append-to-body="false"
        >
          <div>
            <el-form ref="form" :model="form" label-width="80px">
              <el-form-item label="用户名">
                <el-input v-model="form.username"></el-input>
              </el-form-item>
              <el-form-item label="密码">
                <el-input v-model="form.password"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="createUser">立即创建</el-button>
                <el-button @click="showAddUser = false">取消</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-dialog>
      </div>
    </div>
    <el-dialog
      top="10px"
      width="600px"
      title="重置密码"
      :visible.sync="showAddGroup"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
    >
      <div>
        <el-form ref="form" style="width: 500px" :model="form" label-width="80px">
          <el-form-item label="用户名">
            <el-input v-model="user.name" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="新密码">
            <el-input v-model="user.password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="resetPassWord">确定</el-button>
            <el-button @click="showAddGroup = false">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss">
.role-item {
  width: 200px;
  border-radius: 50%;
  background: #ddd;

  width: 100px;
  height: 100px;
}
.role-choose {
  width: 100%;
  text-align: center;
  padding: 40px 20px;
  box-sizing: border-box;
  border-radius: 8px;
  color: #666;
  font-size: 14px;
  overflow: auto;
}
.root-item {
  text-align: left;
  color: #666;
  background-color: #fff;
  padding: 10px;
  border-radius: 6px;
  font-size: 14px;
}
.role-container {
  display: inline-block;
  vertical-align: top;
  margin: 0 10px;
  p {
    margin: 12px 0;
  }
}
.btn-line {
  padding: 10px 0;
}
.float-btn {
  float: right;
  margin: 10px 0;
}
.tag-item {
  margin-right: 10px;
}
.select-line {
  text-align: left;
  padding-bottom: 20px;
}
.basics-item {
  background-color: #fff;
  padding: 10px 0;
}
</style>
<script>
import { getData, postData } from '@/service/getData';
import log from '@/components/log.vue';
import roleManage from '@/components/role-manage.vue';

export default {
  data() {
    return {
      role: '管理员',
      activeName: 'first',
      showAddUser: false,
      showAddGroup: false,
      currentUser: '',
      form: {
        username: '',
        password: '',
      },
      group: {
        groupname: '',
      },
      user: {
        name: '',
        password: '',
      },
      groupList: [],
      permissionList: [],
      groupData: [],
      tableData: [],
    };
  },
  components: {
    log,
    roleManage,
  },
  mounted() {
    this.role = this.$store.state.user.groups[0] ? this.$store.state.user.groups[0].name : '游客'; // 假设用户的角色存储在 user.groups 中，你需要根据实际情况修改这一行代码来获取用户的角色。
    this.getUserList();
    this.getGroupList();
    this.getPermissionList();
  },
  methods: {
    editUserFile(obj) {
      // 查询用户权限
      // 打开弹窗
      this.currentUser = '';
      setTimeout(() => {
        this.currentUser = obj.id;
      }, 200);
    },
    handleClickReset(username) {
      this.user.name = username;
      this.showAddGroup = true;
    },
    // 将用户添加值分组
    handleChangeGroup(username, groupList) {
      postData(
        '/rbac/user/user_groups_set',
        {
          username: username,
          groups: [groupList],
        },
        'post',
        {
          headers: { 'Content-Type': 'application/json;charset=UTF-8' },
        },
      ).then((res) => {
        // 成功后跳转到登录页
        this.$message.success('分组设置成功');
        this.getUserList();
      });
    },

    handleChangePermission(username, permissionList) {
      postData(
        '/rbac/user/user_perms_set',
        {
          username: username,
          perms: permissionList,
        },
        'post',
        {
          headers: { 'Content-Type': 'application/json;charset=UTF-8' },
        },
      ).then((res) => {
        // 成功后跳转到登录页
        this.$message.success('权限设置成功');
        this.getUserList();
      });
    },
    handleChangePermission_group(username, permissionList) {
      postData(
        '/rbac/group/group_perms_set',
        {
          groupname: username,
          perms: permissionList,
        },
        'post',
        {
          headers: { 'Content-Type': 'application/json;charset=UTF-8' },
        },
      ).then((res) => {
        // 成功后跳转到登录页
        this.$message.success('权限设置成功');
        this.getGroupList();
      });
    },
    // 获取分组信息
    getGroupList() {
      postData('/rbac/group/get_group_list', {}, 'post', {
        headers: { 'Content-Type': 'application/json;charset=UTF-8' },
      }).then((res) => {
        // 过滤掉超级管理员
        res.groups = res.groups.filter((item) => item.name !== '超级管理员');
        this.groupList = res.groups;
      });
    },
    // 将用户移出分组
    // 将用户分组置空

    // 权限列表
    getPermissionList() {
      postData('/rbac/permission/get_permission_list', {}, 'post', {
        headers: { 'Content-Type': 'application/json;charset=UTF-8' },
      }).then((res) => {
        // 成功后跳转到登录页
        this.permissionList = res.permissions;
      });
    },
    // 用户是否有当前权限
    // 用户添加权限
    // 用户移出某权限
    // 用户清除全部权限

    // 重置密码
    resetPassWord() {
      postData(
        '/rbac/user/set_password',
        {
          username: this.user.name,
          new_password: this.user.password,
        },
        'post',
        {
          headers: { 'Content-Type': 'application/json;charset=UTF-8' },
        },
      ).then((res) => {
        // 成功后跳转到登录页
        this.$message.success('密码重置成功');
        this.showAddGroup = false;
        this.user = {
          name: '',
          password: '',
        };
        this.getUserList();
      });
    },
    // 获取用户信息
    // 删除用户
    dellteUser(username) {
      postData('/rbac/user/delete_user', { username }, 'post', {
        headers: { 'Content-Type': 'application/json;charset=UTF-8' },
      }).then((res) => {
        // 成功后跳转到登录页
        this.$message.success('删除成功');
        this.getUserList();
      });
    },
    dellteGroup(groupname) {
      postData('/rbac/group/remove_group', { groupname }, 'post', {
        headers: { 'Content-Type': 'application/json;charset=UTF-8' },
      }).then((res) => {
        // 成功后跳转到登录页
        this.$message.success('删除成功');
        this.getGroupList();
      });
    },
    // 创建用户
    getUserList() {
      postData('/rbac/user/get_user_list').then((res) => {
        // 过滤掉当前用户
        res.user_list = res.user_list.filter(
          (item) => item.username !== this.$store.state.user.username,
        );
        this.tableData = res.user_list;
        this.tableData.forEach((item) => {
          console.log(item.groups, item);
          item.groups = item.groups[0];
        });
      });
    },
    // 登出
    logout() {
      postData('/rbac/auth/logout')
        .then((res) => {
          // 成功后跳转到登录页
          this.$router.push('/login');
        })
        .catch((err) => {
          // 失败后跳转到登录页
          this.$router.push('/login');
        });
    },

    getUserInfo() {
      // /rbac/user/get_user_info
      postData('/rbac/user/get_user_info', { username: this.$store.state.user.username }, 'post', {
        headers: { 'Content-Type': 'application/json;charset=UTF-8' },
      }).then((res) => {
        // 成功后跳转到登录页
        this.$store.commit('setUser', res.user);
      });
    },
    createUser() {
      //  将参数转为 json

      postData(
        '/rbac/user/create_user',
        {
          ...this.form,
        },
        'post',
        {
          headers: { 'Content-Type': 'application/json;charset=UTF-8' },
        },
      )
        .then((res) => {
          // 成功后跳转到登录页
          this.$message.success('创建成功');
          this.showAddUser = false;
          this.getUserList();
          // 未创建成功的用户分配角色
          this.handleChangeGroup(this.form.username, '普通用户');
          this.form = {
            username: '',
            password: '',
          };
        })
        .catch((err) => {
          this.$message.error('创建失败,请检查用户信息是否正确');
        });
    },
    createGroup() {
      //  将参数转为 json

      postData(
        '/rbac/group/create_group',
        {
          groupname: this.group.groupname,
        },
        'post',
        {
          headers: { 'Content-Type': 'application/json;charset=UTF-8' },
        },
      ).then((res) => {
        // 成功后跳转到登录页
        this.$message.success('创建成功');
        this.showAddGroup = false;
        this.getGroupList();
      });
    },
  },
};
</script>
